package eerbaar.client.internal.exp;

import java.util.HashMap;
import java.util.Map;

import eerbaar.client.exp.IState;

import eerbaar.shared.tree.INode;
import eerbaar.shared.tree.NodeCmdFactory;
import eerbaar.shared.tree.NodeFactory;

public class State implements IState {

    private String error;

    private boolean errorFlag;

    private boolean finished;

    private final Map<String, String> map = new HashMap<String, String>();

    public State() {
        //
    }

    @Override
    public String getError() {
        return this.error;
    }

    @Override
    public String getProperty(String key) {

        return this.map.get(key);
    }

    @Override
    public boolean isError() {
        return this.errorFlag;
    }

    @Override
    public boolean isFinished() {

        return this.finished;
    }

    public void load(INode parent) {

        INode child = NodeCmdFactory.findChild(parent, "state");
        if (child == null) {
            return;
        }

        String value = child.getPayload().getValue();
        if (value.length() == 0) {
            return;
        }

        this.map.clear();
        String[] parts = value.split(",");
        for (String part : parts) {
            String[] e = part.split("=");
            String k = e[0];
            String v = e[1];
            this.map.put(k, v);
        }

    }

    public void save(INode parent) {

        String data = "";
        String[] set = this.map.keySet().toArray(new String[] {});
        for (int i = 0; i < set.length; i++) {
            String k = set[i];
            String v = this.map.get(k);

            if (v == null) {
                continue;
            }

            if (data.length() > 0) {
                data += ",";
            }
            v = v.replace(',', ' ');
            data += k + "=" + v;
        }

        INode node = NodeFactory.create("state", data);
        INode old = NodeCmdFactory.findChild(parent, "state");
        if (old != null) {

            NodeCmdFactory.remove(parent, old);
        }
        NodeCmdFactory.add(parent, node);
    }

    @Override
    public void setError(String error) {
        this.error = error;
    }

    @Override
    public void setErrorFlag(boolean errorFlag) {
        this.errorFlag = errorFlag;
    }

    @Override
    public void setFinished(boolean finished) {
        this.finished = finished;
    }

    @Override
    public void setProperty(String key, String value) {

        this.map.put(key, value);
    }

    @Override
    public String toString() {

        return this.map.toString();
    }

}
